package rpg.map;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import rpg.Rpg;
import rpg.script.EffectScriptImpl;
import square.data.DataGroup;
import square.data.EffectData;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class Effect extends MapObject {

	private Timer timer;
	private EffectScriptImpl script;
	private Integer repeat = 0;
	private Color color = Color.white;

	// Creation
	public Effect(String name, int time) {
		this.setDataReflect(DataGroup.findEffect(name));
		this.setData(this.getDataReflect().instance());
		this.getData().setOwner(this);

		final Effect effect = this;
		timer = new Timer(time, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {				
				if (getData().getRepeat() != -1)
					setRepeat(getRepeat() + 1);
				
				if(getData().getRepeat() == getRepeat()) {
					effect.removeFromMap();
				}
			}
		});

		if (this.getData().getScript() != null) {
			this.setScript((EffectScriptImpl) this.getData().getScript()
					.instance());
			this.getScript().setObject(this);
		}
	}

	// Use Event
	public boolean onUse(Location location) {
		if(Rpg.disableEvents)
			return false;
		
		timer.start();

		if (this.getScript() != null) {
			return this.getScript().onUse(location);
		}
		return true;
	}

	// Paint Event
	public boolean onPaint(Object context) {
		if(Rpg.disableEvents)
			return false;
		
		if (this.getScript() != null) {
			return this.getScript().onPaint(context);
		}
		return true;
	}

	// Map Shortcut
	@Override
	public void removeFromMap() {
		if (this.getLocation() != null) {
			this.getLocation().removeEffect(this);
		}
	}

	// Get & Set
	@Override
	public final EffectData getData() {
		return (EffectData) super.getData();
	}

	@Override
	public final EffectData getDataReflect() {
		return (EffectData) super.getDataReflect();
	}

	public Timer getTimer() {
		return timer;
	}

	public void setTimer(Timer timer) {
		this.timer = timer;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public EffectScriptImpl getScript() {
		return script;
	}

	public void setScript(EffectScriptImpl script) {
		this.script = script;
	}

	public Integer getRepeat() {
		return repeat;
	}

	public void setRepeat(Integer repeat) {
		this.repeat = repeat;
	}
}
